import {
  useEffect,
  useState,
  forwardRef,
  useImperativeHandle,
  useMemo,
  useRef,
} from 'react';
import { Tabs, ConfigProvider } from 'antd';
import {commonLang} from '@inbiz/utils'
import { GlobalRegistry } from '@inbiz/core';
import { getEditor, getHashString } from '@inbiz/utils';
import SearchBar from '../SearchBar';
import ProcessApply from './components/ProcessApply';
import ProcessInfomation from './components/ProcessInfomation';
import { TextWidget, getMessage } from '@inbiz/react';
import './style.less';

interface centerIndexProps {
  userInfo: {
    ID: string;
  };
  tabsArr: any[];
  showTabTitle?: boolean;
  defaultpage: string;
  rangeConfig: string;
  processGroup: any;
  openMode: string;
  ifQuickApproval: boolean;
  openPopUpHeight: {
    value: string;
    type: string;
  };
  openPopUpWidth: {
    value: string;
    type: string;
  };
  drawerWidth: {
    value: string;
    type: string;
  };
  getApplyCategory: any;
  getGroup: any;
  getApplyList: any;
  getMyToDo: any;
  getApplying: any;
  getDraft: any;
  getToMe: any;
  getMyApply: any;
  getHaveDone: any;
  getClassification: any;
  configEvents: any;
  customClickItem: any;
}

const { TabPane } = Tabs;

const CenterIndex = forwardRef((props: centerIndexProps, ref) => {
  const {
    userInfo,
    tabsArr,
    showTabTitle,
    defaultpage,
    rangeConfig,
    processGroup,
    openMode,
    openPopUpHeight,
    openPopUpWidth,
    drawerWidth,
    ifQuickApproval,
    getApplyCategory,
    getGroup,
    getApplyList,
    getMyToDo,
    getApplying,
    getDraft,
    getToMe,
    getMyApply,
    getHaveDone,
    getClassification,
    configEvents,
    customClickItem,
  } = props;

  const hashTabkey = getHashString('tabKey');
  const isEditor = getEditor();
  const nowDefaultKey = hashTabkey && !isEditor ? hashTabkey : defaultpage;
  const [choosedTabKey, $choosedTabKey] = useState(nowDefaultKey);

  const searchBarRef = useRef<any>();
  const applyRef = useRef<any>();
  const processInfomationRef = useRef<any>();

  const [locale, $locale] = useState(commonLang[GlobalRegistry.getDesignerLanguage()?.toLocaleLowerCase() as keyof typeof commonLang])
  useEffect(() => {
    $locale(commonLang[GlobalRegistry.getDesignerLanguage()?.toLocaleLowerCase() as keyof typeof commonLang])
  }, [GlobalRegistry.getDesignerLanguage()]);

  const _placeholder = useMemo(() => {
    switch(choosedTabKey){
      case '1':
      case '4':
        return getMessage('Processcenter.placeholder1');
      case '2':
      case '5':
      case '7':
      case '8':
        return getMessage('Processcenter.placeholder2');
      case '3':
      case '6':
        return getMessage('Processcenter.placeholder3');
      default:
        return getMessage('Processcenter.searchProcess');
    }
  }, [choosedTabKey, locale]);

  const changeTab = (key: string) => {
    sessionStorage.removeItem('batchApproval');
    searchBarRef?.current?.$searchText('');
    $choosedTabKey(key);
    const href = window.location.href;
    const equalIndex = href.indexOf('tabKey');
    if (equalIndex > -1) {
      const newHref = href.slice(0, equalIndex + 7) + key;
      window.history.replaceState({}, '', `${newHref}`);
    } else {
      window.history.replaceState({}, '', `${href}/p?tabKey=${key}`);
    }
  };

  useImperativeHandle(ref, () => ({
    getCategory: applyRef?.current?.getApplyCategory,
    searchApply: applyRef?.current?.searchApply,
  }));

  useEffect(() => {
    if (nowDefaultKey) {
      changeTab(nowDefaultKey);
    } else {
      changeTab(tabsArr[0].id);
    }
  }, [tabsArr, nowDefaultKey]);

  const onSearchText = () => {
    if (choosedTabKey == '1') {
      applyRef?.current?.searchApply(searchBarRef?.current?.searchText);
    } else {
      processInfomationRef?.current?.searchInfo(searchBarRef?.current?.searchText);
    }
  };

   // 发起申请的属性
   const applyProps = {
    openMode,
    openPopUpHeight,
    openPopUpWidth,
    drawerWidth,
    choosedTabKey,
    searchBarRef,
    userInfo,
    rangeConfig,
    processGroup,
    getApplyCategory,
    getApplyList,
  };

  // 非发起申请属性
  const ProcessInfomationProps = {
    tabsArr,
    choosedTabKey,
    userInfo,
    showTabTitle,
    rangeConfig,
    processGroup,
    openMode,
    openPopUpHeight,
    openPopUpWidth,
    drawerWidth,
    searchBarRef,
    ifQuickApproval,
    getGroup,
    getMyToDo,
    getApplying,
    getDraft,
    getToMe,
    getMyApply,
    getHaveDone,
    getClassification,
    configEvents,
    customClickItem,
  };

  return (
    <div className="inbiz-CenterIndex">
      <ConfigProvider locale={locale}>
        <Tabs
          className={showTabTitle ? '' : 'noTabTitle'}
          defaultActiveKey={defaultpage}
          onChange={changeTab}
          activeKey={choosedTabKey}
          destroyInactiveTabPane={true}
        >
          {tabsArr.map((item: { title: string; id: string }) => {
            return (
              <TabPane
                tab={showTabTitle ? <TextWidget>{item.title}</TextWidget> : ''}
                key={item.id}
              >
                <>
                  <SearchBar
                    ref={searchBarRef}
                    onSearch={() => {
                      onSearchText();
                    }}
                    placeholder={_placeholder}
                  />
                  {item.id == '1' ? (
                    <ProcessApply
                      ref={applyRef}
                      data={item}
                      {...applyProps}
                    />
                  ) : (
                    <ProcessInfomation
                      ref={processInfomationRef}
                      {...ProcessInfomationProps}
                    />
                  )}
                </>
              </TabPane>
            );
          })}
        </Tabs>
      </ConfigProvider>
    </div>
  );
},
);

export default CenterIndex;
